package com.deeper.customview.ui.c2.demo.c02d01;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

public class BallMoveView extends View {
    /**
     * 小球水平位置
     */
    private int x;
    /**
     * 小球垂直位置，固定为100
     */
    private static final int Y = 100;
    /**
     * 小球半径
     */
    private static final int RADIUS = 100;
    /**
     * 小球颜色
     */
    private static final int COLOR = Color.RED;
    /**
     * 移动方向
     */
    private boolean direction;

    private Paint paint;


    public BallMoveView(Context context) {
        super(context);
    }


    public BallMoveView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //初始化画笔
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(COLOR);
        x = RADIUS;
    }


    public BallMoveView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //根据x, y绘制一个球
        canvas.drawCircle(x, Y, RADIUS, paint);
        //改变x坐标的值，调用invalidate()后，
        //小球将因x的值发生改变而产生移动的效果
        int width = this.getMeasuredWidth(); //获取组件的宽度
        if (x < RADIUS) {
            direction = true;
        }
        if (x > width - RADIUS) {
            direction = false;
        }
        x = direction ? x + 5 : x - 5;
    }
}
